<template>
    <div>
      <h1>学生管理</h1>
      <el-button @click="addStudentButtonClick">添加学生</el-button>
      <el-table :data="studentStore.students" stripe>
        <el-table-column prop="name" label="学生姓名"></el-table-column>
        <el-table-column prop="studentNumber" label="学号"></el-table-column>
        <el-table-column prop="major" label="专业"></el-table-column>
        <el-table-column prop="enrollmentDate" :formatter="dateFormat" label="入学日期"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="editStudent(scope.$index)">编辑</el-button>
            <el-button @click="deleteStudent(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
      :current-page="studentStore.currentPage"
      :page-size="studentStore.pageSize"
      :total="studentStore.total"
      @current-change="handleCurrentChange"
      layout="total, prev, pager, next"
    />
      <el-dialog v-model="addStudentModal" title="添加学生">
          <el-form :rules="rules" :model="studentForm" ref="studentFormRef" label-width="80px">
            <el-form-item label="学生姓名" prop="name">
              <el-input v-model="studentForm.name" ></el-input>
            </el-form-item>
            <el-form-item label="学号" prop="studentNumber">
              <el-input v-model="studentForm.studentNumber" ></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="studentForm.gender">
            <el-radio value="男">男</el-radio>
            <el-radio value="女">女</el-radio>
          </el-radio-group>
            </el-form-item>
            <el-form-item label="专业" prop="major">
              <el-input v-model="studentForm.major" ></el-input>
            </el-form-item>
            <el-form-item label="入学日期" prop="enrollmentDate">
                        <el-date-picker
                  v-model="studentForm.enrollmentDate"
                  type="datetime"
                  placeholder="入学日期"
                />
            </el-form-item>
          </el-form>
        <template #footer>
          <el-button @click="addStudentModal = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
<script setup lang="ts">
import { ref } from 'vue';
import { useStudentStore } from '../stores/student';
import { ElButton, ElTable, ElTableColumn, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus';
  
import type { FormInstance, FormRules } from 'element-plus'
const isEditing = ref(false); // 标记是否处于编辑状态
const currentEditIndex = ref(-1); // 记录当前编辑条目的索引

const studentStore = useStudentStore();
const addStudentModal = ref(false);
const studentForm = ref({
  name: '',
  studentNumber: '',
  gender: '男',
  major: '',
  enrollmentDate: new Date()
});



// 时间格式化
const dateFormat = (row: { enrollmentDate: string | number | Date }): string => {
  let time: Date;
  if (typeof row.enrollmentDate ==='string') {
    time = new Date(row.enrollmentDate);
  } else if (typeof row.enrollmentDate === 'number') {
    time = new Date(row.enrollmentDate);
  } else {
    time = row.enrollmentDate;
  }
  if (!time || isNaN(time.getTime())) {
    return '';
  }
  const year = time.getFullYear();
  const month = dateIfAddZero(time.getMonth() + 1);
  const day = dateIfAddZero(time.getDate());
  return `${year}-${month}-${day}`;
};

const dateIfAddZero = (time: number): string => {
  return time < 10? `0${time}` : `${time}`;
};

const rules = reactive<FormRules<typeof studentForm>>({
  enrollmentDate: [
    { required: true, message: '请选择入学时间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请输入学生专业', trigger: 'blur' }
  ],
  studentNumber: [
    { required: true, message: '请输入学生学号', trigger: 'blur' },
   
  ],
  gender: [
    {required:true, message: '请选择学生性别', trigger: 'blur' }
  ]
});

const studentFormRef = ref<FormInstance>();

const addStudentButtonClick = () => {
  addStudentModal.value = true;
  isEditing.value = false;
  studentForm.value = {
    name: '',
    studentNumber: '',
    gender: '',
    major: '',
    enrollmentDate:new Date()
  };
};


const submitForm = async () => {
  await nextTick();
  studentFormRef.value?.validate(async (valid) => {
    if (valid) {
      if (isEditing.value) {
        // 更新课程信息
        await studentStore.updateStudent(currentEditIndex.value, studentForm.value);
      } else {
        await studentStore.addStudent(studentForm.value);
      }
      addStudentModal.value = false;
      isEditing.value = false;
      studentForm.value = {
        name: '',
        gender: '男',
        major: '',
        enrollmentDate: new Date(),
        studentNumber: ''
      };
    }
  });
};



const editStudent = (index: number) => {
  isEditing.value = true;
  currentEditIndex.value = index;
  addStudentModal.value = true;
  // 将选中条目的信息回显到对话框中
  studentForm.value = { ...studentStore.students[index] };
};

const handleCurrentChange = (page: number) => {
  studentStore.changePage(page);
};

const deleteStudent = (index: number) => {
  studentStore.deleteStudent(index);
};
  </script>